package com.hulman.oms.web;

import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.Accessory;
import com.hulman.oms.service.AccessoryService;
import com.hulman.oms.util.NumberUtil;
import com.hulman.oms.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: maxwellens
 */
@RestController
public class AccessoryController
{
    @Autowired
    private AccessoryService accessoryService;

    @GetMapping("/accessories/{id}")
    public Result findAccessoryById(@PathVariable Integer id)
    {
        Accessory accessory = accessoryService.findAccessoryById(id);
        return new Result(accessory);
    }

    @GetMapping("/accessories")
    public Result findAccessories(Integer page, Integer limit, Integer tunnelId, String system, String type, Integer deviceId, String name, String brand, String model, String productRange)
    {
        Map<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("limit", limit);
        map.put("tunnelId", tunnelId);
        map.put("system", system);
        map.put("type", type);
        map.put("deviceId", deviceId);
        map.put("name", name);
        map.put("brand", brand);
        map.put("model", model);
        if (!StringUtil.isEmpty(productRange))
        {
            String[] dates = productRange.split(" - ");
            map.put("startDate", dates[0]);
            map.put("endDate", dates[1]);
        }
        return accessoryService.findAccessoriesResult(map);
    }

    @DeleteMapping("/accessories/{ids}")
    public Result deleteAccessoryById(@PathVariable String ids)
    {
        int[] idArrays = NumberUtil.parseIntArray(ids);
        for (Integer id : idArrays)
        {
            accessoryService.deleteAccessoryById(id);
        }
        return Result.SUCCESS;
    }

    @DeleteMapping("/accessories")
    public Result clearAccessoriesByDeviceId(Integer deviceId)
    {
        accessoryService.clearAccessoriesByDeviceId(deviceId);
        return Result.SUCCESS;
    }

    @PutMapping("/accessories")
    public Result saveAccessory(Accessory accessory)
    {
        accessoryService.saveAccessory(accessory);
        return Result.SUCCESS;
    }

}
